import { asyncRoutes, constantRoutes, async404 } from '@/router'

/**
 * 递归过滤不符合权限的路由
 * @param {*} routes
 * @param {*} auths
 */
function filterAsyncRoutes(routes, auths, level) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (findRouter(auths, tmp.name) || level > 1) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, auths, level + 1)
      }
      res.push(tmp)
    }
  })
  return res
}

function findRouter(auths, name) {
  let isHas = false
  auths.forEach((item) => {
    if (item.menuUrl === name) {
      isHas = true
      return true
    }
  })
  return isHas
}

const state = {
  routes: [],
  addRoutes: [],
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  HIDE_ROUTES: (state, routes) => {
    state.routes = routes
  },
}

function flatAuths(authPageRoutes) {
  let auths = []
  authPageRoutes.forEach((item) => {
    auths.push(item)
    if (Array.isArray(item.menus) && item.menus.length > 0) {
      auths = auths.concat(flatAuths(item.menus))
      // 删掉多余的子节点
      delete item.menus
    }
  })
  return auths
}

const actions = {
  generateRoutes({ commit }, authPageRoutes) {
    return new Promise((resolve) => {
      const auths = flatAuths(authPageRoutes)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, auths, 0)
      commit('SET_ROUTES', accessedRoutes.concat(async404))
      resolve(accessedRoutes.concat(async404))
    })
  },
  // 隐藏部分侧边栏
  hideRoutes({ commit }, routes) {
    return new Promise((resolve) => {
      commit('HIDE_ROUTES', routes)
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
